<template>
  <div class="meeting-container">
    <el-card class="meeting-card">
      <template #header>
        <div class="meeting-header">
          <h1>会议管理</h1>
          <el-form :inline="true" class="meeting-filter" @submit.prevent="searchMeetings">
            <el-form-item label="会议名称">
              <el-input v-model="filters.meetingName" placeholder="请输入会议名称" clearable />
            </el-form-item>
            <el-form-item label="创建人">
              <el-input v-model="filters.creatPerson" placeholder="请输入创建人" clearable />
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker v-model="filters.startTime" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchMeetings" :loading="loading">查询</el-button>
              <el-button type="success" @click="showCreateDialog" :loading="loading">创建会议</el-button>
              <el-button type="warning" @click="exportToExcel" :loading="loading">导出Excel</el-button>
              <el-button type="danger" @click="confirmBatchDelete" :loading="loading"
                :disabled="selectedMeetings.length === 0">批量删除</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <el-table :data="meetings" style="width: 100%" v-loading="loading" border stripe
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="isSelectable" />
        <el-table-column prop="meetingName" label="会议名称" />
        <el-table-column prop="creatPerson" label="创建人" />
        <el-table-column label="会议状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row)">{{ getMeetingStatus(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 审核状态列 - 所有用户可见 -->
        <el-table-column label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getReviewStatusType(scope.row.meetingStatus)">
              {{ getReviewStatusText(scope.row.meetingStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间">
          <template #default="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="会议内容" show-overflow-tooltip>
          <template #default="scope">
            {{ stripHtmlTags(scope.row.meetingCcontent || scope.row.meetingContent || '') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <div class="action-buttons">
              <!-- 基础操作按钮 - 只有管理员或会议创建者可以操作 -->
              <el-button v-if="isAdmin || scope.row.creatPersonId === currentUserId" size="small" type="primary"
                @click="showEditDialog(scope.row)" :disabled="loading">
                修改
              </el-button>
              <el-button size="small" type="info" @click="viewMeetingDetails(scope.row)"
                :disabled="loading">详情</el-button>

              <!-- 审核操作下拉菜单 - 只有管理员可见，且只对未审核的会议显示 -->
              <el-dropdown v-if="isAdmin && scope.row.meetingStatus === 0" @command="handleReviewCommand"
                :disabled="loading">
                <el-button size="small" type="success">
                  审核操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'approve', meetingId: scope.row.meetingId }">
                      <el-icon>
                        <check />
                      </el-icon>审核通过
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'reject', meetingId: scope.row.meetingId }">
                      <el-icon>
                        <close />
                      </el-icon>审核拒绝
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <!-- 删除按钮 - 只有管理员或会议创建者可以删除 -->
              <el-button v-if="isAdmin || scope.row.creatPersonId === currentUserId" size="small" type="danger"
                @click="confirmDelete(scope.row.meetingId)" :disabled="loading">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="meetings.length === 0" class="no-data">
        <el-empty description="暂无会议数据" />
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination v-model:current-page="currentPage" :page-size="10" :total="total"
          layout="total, prev, pager, next, jumper" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 创建/编辑会议弹窗 -->
    <el-dialog :title="isEdit ? '修改会议' : '创建会议'" v-model="dialogVisible" width="50%" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="currentMeeting" label-width="100px">
        <el-form-item label="会议名称" required>
          <el-input v-model="currentMeeting.meetingName" placeholder="请输入会议名称" />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="currentMeeting.creatPerson" placeholder="请输入创建人" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="会议封面">
          <div class="image-upload-container">
            <el-input v-model="currentMeeting.meetingCover" placeholder="请输入图片名称或选择图片" readonly class="image-input" />
            <el-button type="primary" @click="selectImage" class="select-image-btn">
              选择图片
            </el-button>
            <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleImageSelect" />
          </div>
          <div class="form-tip">支持 jpg、png、gif 等图片格式</div>
          <div v-if="currentMeeting.meetingCover" class="image-preview">
            <img :src="getMeetingCoverUrl(currentMeeting.meetingCover)" :alt="currentMeeting.meetingCover"
              @error="handleImageError" />
            <span class="image-name">{{ currentMeeting.meetingCover }}</span>
          </div>
        </el-form-item>
        <el-form-item label="开始时间" required>
          <el-date-picker v-model="meetingStartTime" type="datetime" placeholder="选择日期时间" format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm" />
        </el-form-item>
        <el-form-item label="结束时间" required>
          <el-date-picker v-model="meetingEndTime" type="datetime" placeholder="选择日期时间" format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm" />
        </el-form-item>
        <el-form-item label="会议内容">
          <div class="editor-container">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 350px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="handleCreated" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" :disabled="loading">取消</el-button>
          <el-button type="primary" @click="saveMeeting" :loading="loading">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 会议详情弹窗 -->
    <el-dialog title="会议详情" v-model="detailsVisible" width="60%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="会议名称">{{ currentMeeting.meetingName }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ currentMeeting.creatPerson }}</el-descriptions-item>
        <el-descriptions-item label="会议状态">
          <el-tag :type="getStatusType(currentMeeting)">{{ getMeetingStatus(currentMeeting) }}</el-tag>
        </el-descriptions-item>
        <!-- 审核状态 - 所有用户可见 -->
        <el-descriptions-item label="审核状态">
          <el-tag :type="getReviewStatusType(currentMeeting.meetingStatus)">
            {{ getReviewStatusText(currentMeeting.meetingStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ formatDate(currentMeeting.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ formatDate(currentMeeting.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="会议封面">
          <div class="cover-container">
            <el-image v-if="currentMeeting.meetingCover" :src="getMeetingCoverUrl(currentMeeting.meetingCover)"
              fit="contain" :preview-src-list="[getMeetingCoverUrl(currentMeeting.meetingCover)]"
              @error="handleImageError" />
            <span v-else>无封面</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="会议内容">
          <div class="meeting-content"
            v-html="currentMeeting.meetingCcontent || currentMeeting.meetingContent || '暂无内容'">
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDetailsDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog title="确认删除" v-model="deleteConfirmVisible" width="30%">
      <p v-if="meetingIdToDelete">确定要删除此会议吗？此操作不可撤销。</p>
      <p v-else>确定要删除选中的 {{ selectedMeetings.length }} 个会议吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDelete" :disabled="loading">取消</el-button>
          <el-button type="danger" @click="deleteMeeting" :loading="loading">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, shallowRef, onBeforeUnmount, computed } from 'vue'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import { ArrowDown, Check, Close } from '@element-plus/icons-vue'
import MeetingService from '../services/MeetingService.js'
import UserService from '../services/UserService.js'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 响应式数据
const meetings = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const detailsVisible = ref(false)
const deleteConfirmVisible = ref(false)
const meetingIdToDelete = ref(null)
const isEdit = ref(false)
const selectedMeetings = ref([])
const fileInput = ref(null)

// 当前用户信息 - 使用UserService
const currentUserId = computed(() => UserService.getCurrentUserId())
const isAdmin = computed(() => UserService.isAdmin())

const isSelectable = computed(() => {
  return (row) => {
    // 如果是管理员，所有行都可选
    const currentUserStr = localStorage.getItem('currentUser');

    if (JSON.parse(currentUserStr).userType === 2) return true

    // 否则，只有自己创建的会议可选
    return row.creatPersonId === currentUserId.value
  }
})

// 分页相关数据
const currentPage = ref(1)
const total = ref(0)




// 富文本编辑器相关
const editorRef = shallowRef()
const valueHtml = ref('<p>请输入会议内容...</p>')
const mode = ref('default')
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入会议内容...',
  MENU_CONF: {}
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor
}

// 筛选条件
const filters = reactive({
  meetingName: '',
  creatPerson: '',
  startTime: ''
})

// 当前操作的会议
const currentMeeting = reactive({
  meetingId: null,
  creatPersonId: UserService.getCurrentUserId(), // 使用UserService获取当前用户ID
  meetingName: '',
  creatPerson: UserService.isAdmin() ? '管理员' : '普通用户', // 根据用户权限设置创建人
  startTime: null,
  endTime: null,
  meetingCover: '',
  meetingCcontent: '',
  meetingContent: '',
  meetingStatus: 0 // 新增审核状态字段
})

// 日期时间处理
const meetingStartTime = ref('')
const meetingEndTime = ref('')

// 方法
const loadMeetings = async () => {
  loading.value = true;
  try {
    // 构建查询参数，包含分页信息
    const params = {
      ...filters,
      current: currentPage.value
    };

    const response = await MeetingService.getMeetingsWithPage(params);
    if (response.code === 200) {
      const pageData = response.data;
      meetings.value = pageData.records || [];
      total.value = pageData.total || 0;

      // 格式化日期，确保日期对象可以正确处理
      meetings.value.forEach(meeting => {
        if (meeting.startTime && typeof meeting.startTime === 'string') {
          meeting.startTime = new Date(meeting.startTime);
        }
        if (meeting.endTime && typeof meeting.endTime === 'string') {
          meeting.endTime = new Date(meeting.endTime);
        }

        // 处理内容字段可能的不一致
        if (meeting.meetingContent && !meeting.meetingCcontent) {
          meeting.meetingCcontent = meeting.meetingContent;
        } else if (meeting.meetingCcontent && !meeting.meetingContent) {
          meeting.meetingContent = meeting.meetingCcontent;
        }

        // 确保审核状态字段存在
        if (meeting.meetingStatus === undefined || meeting.meetingStatus === null) {
          meeting.meetingStatus = 0;
        }
      });
    } else {
      ElMessage.error('获取会议列表失败: ' + response.message);
    }
  } catch (error) {
    console.error('获取会议列表失败:', error);
    ElMessage.error('获取会议列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
}

// 搜索会议
const searchMeetings = () => {
  console.log('搜索会议，筛选条件:', filters);

  // 处理日期格式
  if (filters.startTime) {
    // 日期已经由el-date-picker格式化为YYYY-MM-DD格式
    // 添加时间部分以便后端处理
    filters.startTime = `${filters.startTime} 00:00:00`;
    console.log('格式化后的日期:', filters.startTime);
  }

  // 搜索时重置到第一页
  currentPage.value = 1;
  loadMeetings();
}

// 显示创建会议弹窗
const showCreateDialog = () => {
  isEdit.value = false;
  Object.keys(currentMeeting).forEach(key => {
    if (key === 'creatPersonId') {
      currentMeeting[key] = currentUserId.value;
    } else if (key === 'creatPerson') {
      currentMeeting[key] = isAdmin.value ? '管理员' : '普通用户';
    } else if (key === 'meetingStatus') {
      currentMeeting[key] = 0; // 默认为未审核
    } else {
      currentMeeting[key] = '';
    }
  });
  currentMeeting.meetingId = null;
  meetingStartTime.value = '';
  meetingEndTime.value = '';
  valueHtml.value = '<p>请输入会议内容...</p>';
  dialogVisible.value = true;
}

// 显示编辑会议弹窗
const showEditDialog = (meeting) => {
  // 权限验证：只有管理员或会议创建者可以编辑
  if (!isAdmin.value && meeting.creatPersonId !== currentUserId.value) {
    ElMessage.warning('您没有权限修改此会议');
    return;
  }

  isEdit.value = true;
  Object.keys(currentMeeting).forEach(key => {
    currentMeeting[key] = meeting[key] || '';
  });

  // 格式化日期时间
  if (meeting.startTime) {
    const startDate = new Date(meeting.startTime);
    const formattedStartDate = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}-${String(startDate.getDate()).padStart(2, '0')} ${String(startDate.getHours()).padStart(2, '0')}:${String(startDate.getMinutes()).padStart(2, '0')}`;
    meetingStartTime.value = formattedStartDate;
  }
  if (meeting.endTime) {
    const endDate = new Date(meeting.endTime);
    const formattedEndDate = `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}-${String(endDate.getDate()).padStart(2, '0')} ${String(endDate.getHours()).padStart(2, '0')}:${String(endDate.getMinutes()).padStart(2, '0')}`;
    meetingEndTime.value = formattedEndDate;
  }

  valueHtml.value = meeting.meetingCcontent || meeting.meetingContent || '<p>请输入会议内容...</p>';
  dialogVisible.value = true;
}

// 保存会议（创建或更新）
const saveMeeting = async () => {
  // 表单验证
  if (!currentMeeting.meetingName || !meetingStartTime.value || !meetingEndTime.value) {
    ElMessage.warning('请填写必要信息');
    return;
  }

  // 验证富文本内容
  if (!valueHtml.value || valueHtml.value === '<p>请输入会议内容...</p>' || valueHtml.value.trim() === '') {
    ElMessage.warning('请输入会议内容');
    return;
  }

  // 处理日期
  try {
    // 日期已经由el-date-picker格式化为YYYY-MM-DD HH:mm格式
    // 添加秒部分以适配后端API
    currentMeeting.startTime = `${meetingStartTime.value}:00`;
    currentMeeting.endTime = `${meetingEndTime.value}:00`;

    // 检查结束时间是否晚于开始时间
    const startDate = new Date(currentMeeting.startTime);
    const endDate = new Date(currentMeeting.endTime);

    if (endDate <= startDate) {
      ElMessage.warning('结束时间必须晚于开始时间');
      return;
    }
  } catch (e) {
    console.error('日期处理错误:', e);
    ElMessage.error('日期格式错误，请重新选择');
    return;
  }

  // 设置创建者ID
  currentMeeting.creatPersonId = currentUserId.value;

  // 添加调试信息
  console.log('Meeting.vue - 当前用户ID:', currentUserId.value);
  console.log('Meeting.vue - 当前用户ID类型:', typeof currentUserId.value);
  console.log('Meeting.vue - 设置后的creatPersonId:', currentMeeting.creatPersonId);

  // 将富文本内容同步到currentMeeting
  currentMeeting.meetingCcontent = valueHtml.value;
  currentMeeting.meetingContent = valueHtml.value;

  loading.value = true;
  try {
    let response;
    if (isEdit.value) {
      // 更新会议
      response = await MeetingService.updateMeeting(currentMeeting);
    } else {
      // 创建会议 - 传递当前用户ID
      response = await MeetingService.createMeeting(currentMeeting, currentUserId.value);
    }

    if (response.code === 200) {
      ElMessage.success(response.message || '操作成功');
      loadMeetings();
      closeDialog();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('保存会议失败:', error);
    ElMessage.error('保存会议失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
}

// 审核会议
const reviewMeeting = async (meetingId, status) => {
  const statusText = status === 1 ? '通过' : '拒绝';

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}这个会议吗？`,
      '确认审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    loading.value = true;
    const response = await MeetingService.reviewMeeting(meetingId, status);

    if (response.code === 200) {
      ElMessage.success(response.message || `审核${statusText}成功`);
      loadMeetings();
    } else {
      ElMessage.error(response.message || `审核${statusText}失败`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核会议失败:', error);
      ElMessage.error('审核会议失败，请检查网络连接');
    }
  } finally {
    loading.value = false;
  }
}

// 处理审核下拉菜单命令
const handleReviewCommand = (command) => {
  const { action, meetingId } = command;
  const status = action === 'approve' ? 1 : 2;
  reviewMeeting(meetingId, status);
}

// 去除HTML标签，显示纯文本
const stripHtmlTags = (html) => {
  if (!html) return '';
  // 创建临时DOM元素来解析HTML
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  // 获取纯文本内容
  const text = tempDiv.textContent || tempDiv.innerText || '';
  // 去除多余的空格和换行
  return text.trim().replace(/\s+/g, ' ');
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  valueHtml.value = '<p>请输入会议内容...</p>';
}

// 确认删除
const confirmDelete = (meetingId) => {
  // 找到要删除的会议
  const meeting = meetings.value.find(m => m.meetingId === meetingId);
  if (!meeting) {
    ElMessage.error('会议不存在');
    return;
  }

  // 权限验证：只有管理员或会议创建者可以删除
  if (!isAdmin.value && meeting.creatPersonId !== currentUserId.value) {
    ElMessage.warning('您没有权限删除此会议');
    return;
  }

  meetingIdToDelete.value = meetingId;
  deleteConfirmVisible.value = true;
}

// 删除会议（支持单个和批量删除）
const deleteMeeting = async () => {
  loading.value = true;
  try {
    let response;
    if (meetingIdToDelete.value) {
      // 单个删除
      response = await MeetingService.deleteMeeting(meetingIdToDelete.value);
    } else {
      // 批量删除
      const meetingIds = selectedMeetings.value.map(meeting => meeting.meetingId);
      // 这里需要后端支持批量删除接口，暂时使用循环删除
      const results = [];
      for (const id of meetingIds) {
        const result = await MeetingService.deleteMeeting(id);
        results.push(result);
      }

      const successCount = results.filter(r => r.code === 200).length;
      if (successCount === meetingIds.length) {
        response = { code: 200, message: `成功删除 ${successCount} 个会议` };
      } else {
        response = { code: 500, message: `部分删除失败，成功删除 ${successCount} 个会议` };
      }
    }

    if (response.code === 200) {
      ElMessage.success(response.message || '删除成功');
      loadMeetings();
      selectedMeetings.value = [];
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除会议失败:', error);
    ElMessage.error('删除会议失败，请检查网络连接');
  } finally {
    loading.value = false;
    deleteConfirmVisible.value = false;
    meetingIdToDelete.value = null;
  }
}

// 取消删除
const cancelDelete = () => {
  deleteConfirmVisible.value = false;
  meetingIdToDelete.value = null;
}

// 查看会议详情
const viewMeetingDetails = (meeting) => {
  Object.keys(currentMeeting).forEach(key => {
    currentMeeting[key] = meeting[key] || '';
  });
  detailsVisible.value = true;
}

// 关闭详情弹窗
const closeDetailsDialog = () => {
  detailsVisible.value = false;
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedMeetings.value = selection;
}

// 获取会议状态
const getMeetingStatus = (meeting) => {
  if (!meeting.startTime || !meeting.endTime) return '未知';

  const now = new Date();
  const startTime = new Date(meeting.startTime);
  const endTime = new Date(meeting.endTime);

  if (now < startTime) {
    return '未开始';
  } else if (now >= startTime && now <= endTime) {
    return '进行中';
  } else {
    return '已结束';
  }
}

// 获取状态类型
const getStatusType = (meeting) => {
  const status = getMeetingStatus(meeting);
  switch (status) {
    case '未开始':
      return 'info';
    case '进行中':
      return 'success';
    case '已结束':
      return 'danger';
    default:
      return 'info';
  }
}

// 获取审核状态文本
const getReviewStatusText = (status) => {
  switch (status) {
    case 0:
      return '未审核';
    case 1:
      return '已审核';
    case 2:
      return '已拒绝';
    default:
      return '未知';
  }
}

// 获取审核状态类型
const getReviewStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning';
    case 1:
      return 'success';
    case 2:
      return 'danger';
    default:
      return 'info';
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

// 获取会议封面URL
const getMeetingCoverUrl = (coverPath) => {
  if (!coverPath) return '';
  return `/images/${coverPath}`;
}

// 处理图片错误
const handleImageError = (event) => {
  event.target.style.display = 'none';
  event.target.nextSibling.textContent = '图片加载失败';
}

// 确认批量删除
const confirmBatchDelete = () => {
  if (selectedMeetings.value.length === 0) {
    ElMessage.warning('请选择要删除的会议');
    return;
  }

  // 权限验证：普通用户只能删除自己创建的会议
  if (!isAdmin.value) {
    const unauthorizedMeetings = selectedMeetings.value.filter(meeting => meeting.creatPersonId !== currentUserId.value);
    if (unauthorizedMeetings.length > 0) {
      ElMessage.warning('您只能删除自己创建的会议');
      return;
    }
  }

  meetingIdToDelete.value = null; // 标记为批量删除模式
  deleteConfirmVisible.value = true;
}

// 导出Excel
const exportToExcel = async () => {
  try {
    if (meetings.value.length === 0) {
      ElMessage.warning('没有数据可导出');
      return;
    }

    // 导入xlsx库
    const XLSX = await import('xlsx');

    // 准备导出数据
    const exportData = meetings.value.map(meeting => ({
      '会议ID': meeting.meetingId,
      '会议名称': meeting.meetingName,
      '创建人': meeting.creatPerson,
      '开始时间': meeting.startTime ? new Date(meeting.startTime).toLocaleString() : '',
      '结束时间': meeting.endTime ? new Date(meeting.endTime).toLocaleString() : '',
      '会议状态': getMeetingStatus(meeting),
      '审核状态': getReviewStatusText(meeting.meetingStatus),
      '会议内容': stripHtmlTags(meeting.meetingCcontent || meeting.meetingContent || '')
    }));

    // 创建工作簿
    const workbook = XLSX.utils.book_new();

    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData);

    // 设置列宽
    const colWidths = [
      { wch: 10 }, // 会议ID
      { wch: 30 }, // 会议名称
      { wch: 15 }, // 创建人
      { wch: 20 }, // 开始时间
      { wch: 20 }, // 结束时间
      { wch: 12 }, // 会议状态
      { wch: 12 }, // 审核状态
      { wch: 50 }  // 会议内容
    ];
    worksheet['!cols'] = colWidths;

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '会议列表');

    // 生成文件名
    const fileName = `会议列表_${new Date().toISOString().split('T')[0]}.xlsx`;

    // 导出文件
    XLSX.writeFile(workbook, fileName);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  }
}

// 选择图片
const selectImage = () => {
  fileInput.value?.click();
}

// 处理图片选择
const handleImageSelect = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件');
      return;
    }

    // 验证文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片文件大小不能超过5MB');
      return;
    }

    // 获取文件名并存储
    currentMeeting.meetingCover = file.name;

    ElMessage.success(`已选择图片: ${file.name}`);
  }

  // 清空文件输入框，允许重复选择同一文件
  event.target.value = '';
}

// 分页事件处理
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadMeetings();
}

// 生命周期
onMounted(() => {
  UserService.loadCurrentUser();
  loadMeetings();
})
</script>

<style scoped>
.meeting-container {
  padding: 20px;
}

.meeting-card {
  margin-bottom: 20px;
}

.meeting-header {
  display: flex;
  flex-direction: column;
}

.meeting-filter {
  margin-top: 15px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.cover-container {
  max-width: 300px;
}

.meeting-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
}

.no-data {
  padding: 30px 0;
}

.editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
}

.editor-container .w-e-toolbar {
  border-top: none;
  border-left: none;
  border-right: none;
}

.editor-container .w-e-text-container {
  border: none;
}

.meeting-content {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  line-height: 1.6;
  max-height: 300px;
  overflow-y: auto;
}

.meeting-content img {
  max-width: 100%;
  height: auto;
}

.meeting-content p {
  margin: 0 0 10px 0;
}

.meeting-content h1,
.meeting-content h2,
.meeting-content h3,
.meeting-content h4,
.meeting-content h5,
.meeting-content h6 {
  margin: 15px 0 10px 0;
  font-weight: bold;
}

.meeting-content ul,
.meeting-content ol {
  margin: 10px 0;
  padding-left: 20px;
}

.meeting-content li {
  margin: 5px 0;
}

.image-upload-container {
  display: flex;
  align-items: center;
}

.image-input {
  flex: 1;
}

.select-image-btn {
  margin-left: 10px;
}

.image-preview {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.image-preview img {
  max-width: 100px;
  height: auto;
  margin-right: 10px;
}

.image-name {
  font-size: 12px;
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}

.action-buttons .el-dropdown {
  margin: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>